<template>
  <xdh-form class="custom-form"
            :data="formData"
            :model="modelData"
            :mixin="mixin"
            label-width="100px"
            :view="isView"
            :uploadProps="uploadProps"
            @on-submit="handleSubmit"
            v-if="isLoad">
  </xdh-form>
</template>

<style type="text/scss" lang="scss" scoped>
  .custom-form {
    padding: 20px;
  }
</style>

<script>
  import ajax from '@/utils/ajax'
  import {FILE_UPLOAD_PATH} from '@/config'
  import XdhForm from '../../widgets/xdh-form'
  import formFormList from '../../base/mixin/form-form-list'
  import formCustomForm from '../../base/mixin/form-custom-form'
  import sysDictionary from '../../base/mixin/sys-dictionary'
  import {LOCAL, get} from '../../utils/storage'

  const valueRex = function (value) {
    try {
      let Fn = Function;
      return new Fn('return' + value)();
    } catch (e) {
      new Error('请输入正确json格式')
      return value
    }
  }

  const dataToModel = function (data) {
    let model = data || {}
    let value
    Object.keys(model).forEach(item => {
      value = valueRex(model[item])
      if (value) {
        model[item] = valueRex(model[item])
      }
    })
    return model
  }

  /**
   * 表单验证（特殊的验证需要传正则到前端）
   *
   * **** 已实现 ****
   * 输入框
   * 多行文本框
   * 单选
   * 复选
   * 下拉框、级联下拉（如省、市、县的级联下拉框）
   * 时间控件（单个时间、时间段）
   * 批量上传数据（如：批量上传Excel数据）、文件传输 （上传附件及图片。需要考虑批量操作的情况）
   * 时间轴
   * 下拉树 （同步或异步）
   * 步骤
   * 进度条
   *
   * **** 未实现 ****
   * 表单需要动态增、减的项（如：增加一个人员，减少一个人员）
   * 附件下载
   *
   * 暂不用实现
   * 列表 （动态列头，分页）
   */

  // http://localhost:8080/#/customForm?formId=20180622141851197839&taskId=45001&isView=1
  export default {
    components: {
      XdhForm
    },
    mixins: [formFormList, formCustomForm, sysDictionary],
    data() {
      return {
        loginToken: get('token', LOCAL),
        mixin: formCustomForm,
        isLoad: false,
        formData: [],
        modelData: null,
        formId: null,
        isView: false,
        taskId: null
      }
    },
    computed: {
      uploadProps() {
        return {action: FILE_UPLOAD_PATH, headers: {Authorization: this.loginToken.token}}
      }
    },
    methods: {
      // 转换格式
      toData(originData) {
        const formData = originData || []
        // 将级联下拉框的grade转换成branches
        const gradeToBranches = (item) => {
          const grade = item.grade
          this.$set(item, 'branches', {})
          item.options.forEach(opt => {
            if (grade.useMethod === 'dictionary') {
              grade.dictionaryName = opt.name
            }
            this.$set(item.branches, opt.name, [Object.assign({}, grade)])
            if (grade.grade) {
              toData([grade])
            }
          })
        }

        // 将请求字典、请求接口、自定义数据的内容放到options进行渲染，并且对级联下拉框的内容进行处理
        const setOptions = (item, res) => {
          this.$set(item, 'options', res)
          if (item.type === 'select' && item.grade) {
            gradeToBranches(item)
          }
        }

        const toData = (data) => {
          data.forEach(item => {
            if (['select', 'checkbox', 'radio'].indexOf(item.type) > -1) {
              if (item.useMethod === 'dictionary') {
                this.getDictList({dictValue: item.dictionaryName}).then(res => {
                  setOptions(item, res)
                })
              } else if (item.useMethod === 'optionUrl') {
                ajax({
                  method: 'get',
                  url: item.optionUrl
                }).then(res => {
                  setOptions(item, res.data)
                })
              } else {
                setOptions(item, valueRex(item.methodValue))
              }
            }

            if (item.type === 'treeSelect') {
              if (item.useMethod === 'dictionary') {
                this.getTreeList({name: item.dictionaryName}).then(res => {
                  setOptions(item, res)
                })
              }
            }

            if (item.type === 'dynamic') {
              item.children.forEach(col => {
                toData(col)
              })
            }

            if (item.type === 'upload') {
              if (!item.props) {
                this.$set(item, 'props', this.uploadProps)
              } else {
                item.props = Object.assign({}, item.props, this.uploadProps)
              }
            }

            // 处理有分支触发的或者动态增减的表单项
            if (item.branches) {
              Object.keys(item.branches).forEach(branch => {
                toData(item.branches[branch])
              })
            }
          })
        }

        toData(formData)

        return formData
      },
      initCustomForm() {
        this.formId = this.$route.query.formId
        this.isView = Number.parseInt(this.$route.query.isView) === 1
        this.taskId = this.$route.query.taskId
        if (this.formId) {
          this.getFormFormList(this.formId).then(res => {
            this.formData = this.toData(JSON.parse(res.content))
            if (this.taskId) {
              this.getStartVac(this.taskId).then(res => {
                this.modelData = dataToModel(res)
                this.isLoad = true
              })
            } else {
              this.isLoad = true
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: '无效表单模板，加载失败！'
          })
        }
      },
      handleSubmit(model, importData) {
        // 暂时先写死流程信息和用户信息
        const beforeInfo = {
          uorg: '1111',
          userName: 'emp',
          processDefineKey: 'upProcess',
          ajbh: '0001'
        }

        this.startVac(Object.assign({pkValue: this.$route.query.formId}, beforeInfo, model)).then(res => {
          importData.forEach(data => {
            this.submitSelectedExcel(data)
          })
          this.$nextTick(() => {
            this.$message({
              type: 'success',
              message: '保存成功'
            })
          })
        }).catch(err => {
          this.$message({
            message: err + '保存失败!',
            type: 'error'
          })
        })
      }
    },
    created() {
      this.initCustomForm()

      // test
      ajax({
        method: 'get',
        url: 'http://xspttset.s1.natapp.cc/api/myVac?formId=20180629134916146522&list=sqlist&page=1&limit=100'
      }).then(res => {
//        console.log(res)
      })
    }
  }
</script>
